package com.chezai.client.activitys;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.PermissionChecker;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.chezai.client.R;
import com.chezai.client.bean.CheckTime;
import com.chezai.client.bean.ObdConnState;
import com.chezai.client.bean.TerminalBaseInfo;
import com.chezai.client.dao.DaoManager;
import com.chezai.client.dao.manager.TerminalBaseInfoDaoManager;
import com.chezai.client.dao.manager.TerminalParameterDaoManager;
import com.chezai.client.face.APIService;
import com.chezai.client.face.exception.FaceError;
import com.chezai.client.face.model.AccessToken;
import com.chezai.client.face.utils.OnResultListener;
import com.chezai.client.global.Config;
import com.chezai.client.global.Const;
import com.chezai.client.global.DeviceFactory;
import com.chezai.client.global.NetConst;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.global.device.QHYC_C103Hardware;
import com.chezai.client.global.location.LocationMgr;
import com.chezai.client.inter.IWelcomeView;
import com.chezai.client.presenter.WelcomePresenter;
import com.chezai.client.server.TerminalSocketClientManager;
import com.chezai.client.update.AppUpdateManager;
import com.chezai.client.update.OnUpdateListener;
import com.chezai.client.utils.ApnUtils;
import com.chezai.client.utils.AppManager;
import com.chezai.client.utils.DeviceUtils;
import com.chezai.client.utils.MD5Util;
import com.chezai.client.utils.NetworkUtils;
import com.chezai.client.utils.PackageUtils;
import com.chezai.client.utils.PreferenceManager;
import com.chezai.client.utils.ToastUtil;
import com.elm327.MainActivity;
import com.elm327.ObdService;
import com.jx.driving.request.Terminal0x0701Request;
import com.jx.driving.response.Terminal0x8701Response;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;


/**
 * 首页
 * Created by likunyang on 2017/8/24.
 */

public class WelcomeActivity extends BaseActivity<WelcomePresenter, IWelcomeView> implements OnUpdateListener {

    private static int BTN_TIME_TAG = 10001;
    private static int INIT_API_SUCESS = 10002;
    @BindView(R.id.tv_welcome_school_name)
    TextView tvWelcomeSchoolName;
    @BindView(R.id.tv_welcome_id_code)
    TextView tvWelcomeIdCode;
    @BindView(R.id.tv_auth_ing)
    TextView tvAuthing;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.btn_resend)
    Button btnResend;
    private boolean isReady;//相关检测，热点、时间 已检测完毕true
    private boolean isUpdate;//是否升级
    private int locationCount = 0;
    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            if (msg.what == BTN_TIME_TAG) {
                DeviceFactory.hardware.setCalibrateTime();
            } else if (msg.what == INIT_API_SUCESS) {
                ToastUtil.showToast(TerminalApplication.mContext, "启动成功");
            }
            return true;
        }
    });
    private boolean isCheckTimeSucess;

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public int getLayoutId() {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        return R.layout.activity_welcome;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        tvVersion.setText((NetConst.RELEASE_SERVER ? "V " : "TEST_V ") + PackageUtils.getVersionName(new SoftReference<Context>(this)));
        TerminalBaseInfo terminalBaseInfo = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo();
        if (terminalBaseInfo != null) {
            tvWelcomeSchoolName.setText(terminalBaseInfo.getSchoolName() == null ? "" : terminalBaseInfo.getSchoolName());
            tvWelcomeIdCode.setText(terminalBaseInfo.getDevice() == null ? "" : "统一终端ID号（" + terminalBaseInfo.getTraningOrg() + "）");
        }
    }

    @Override
    public void initData() {
        //禁用通知栏
        tvAuthing.setText(R.string.check_device_setting);
        try {
            DeviceFactory.hardware.disableNotificationBar(this);
        } catch (Exception e) {
        }
        NetworkUtils.closeWifiAp(this);//wifi热点如果打开，则关闭
        setupVolume();
        checkApnSetting();//设置APN
        if (Build.VERSION.SDK_INT <= 26) {
            tvAuthing.setText(R.string.check_system_time);
            mHandler.sendEmptyMessageDelayed(BTN_TIME_TAG, 2000);
        } else {
            requestPermissions();
            ActivityCompat.requestPermissions(this, permissionManifest, PERMISSION_REQUEST_CODE);
        }
    }

    private int mNoPermissionIndex = 0;
    private final int PERMISSION_REQUEST_CODE = 1;
    private final String[] permissionManifest = {
            Manifest.permission.CAMERA,
            Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS,
            Manifest.permission.MODIFY_AUDIO_SETTINGS,
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.BLUETOOTH,
//            Manifest.permission.READ_PHONE_STATE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,
//            Manifest.permission.READ_EXTERNAL_STORAGE
    };
    private boolean permissionCheck() {
        int permissionCheck = PackageManager.PERMISSION_GRANTED;
        String permission;
        for (int i = 0; i < permissionManifest.length; i++) {
            permission = permissionManifest[i];
            mNoPermissionIndex = i;
            if (PermissionChecker.checkSelfPermission(this, permission)
                    != PackageManager.PERMISSION_GRANTED) {
                permissionCheck = PackageManager.PERMISSION_DENIED;
            }
        }
        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            return false;
        } else {
            return true;
        }
    }
    private void requestPermissions() {
        List<PermissionItem> permissions = new ArrayList<>();
        permissions.add(new PermissionItem(Manifest.permission.CAMERA, getString(R.string.permission_cus_item_camera), R.drawable.permission_ic_camera));
        permissions.add(new PermissionItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, getString(R.string.permission_cus_item_write), R.drawable.permission_ic_storage));
        permissions.add(new PermissionItem(Manifest.permission.READ_EXTERNAL_STORAGE, getString(R.string.permission_cus_item_read), R.drawable.permission_ic_storage));
        permissions.add(new PermissionItem(Manifest.permission.ACCESS_COARSE_LOCATION, getString(R.string.permission_cus_item_location), R.drawable.permission_ic_location));
        permissions.add(new PermissionItem(Manifest.permission.ACCESS_FINE_LOCATION, getString(R.string.permission_cus_item_location), R.drawable.permission_ic_location));
        permissions.add(new PermissionItem(Manifest.permission.READ_PHONE_STATE, getString(R.string.permission_cus_item_phone), R.drawable.permission_ic_phone));
        //default is normal style
        HiPermission.create(this)
                .permissions(permissions)
                .msg(getString(R.string.permission_msg))
                .animStyle(R.style.PermissionAnimFade)
                .checkMutiPermission(new PermissionCallback() {
                    @Override
                    public void onClose() {

                    }

                    @Override
                    public void onFinish() {

                    }

                    @Override
                    public void onDeny(String permission, int position) {

                    }

                    @Override
                    public void onGuarantee(String permission, int position) {
                        if (TextUtils.equals(permission, Manifest.permission.ACCESS_COARSE_LOCATION)
                                || TextUtils.equals(permission, Manifest.permission.ACCESS_FINE_LOCATION)) {
                            locationCount++;
                        }
                        if (locationCount == 2) {
                            LocationMgr.getInstance();
                            TerminalApplication.getTerminalContext().startUploadGnssService();
                        }
                        if (TextUtils.equals(permission, Manifest.permission.READ_PHONE_STATE)) {
                            tvAuthing.setText(R.string.check_system_time);
                            mHandler.sendEmptyMessageDelayed(BTN_TIME_TAG, 2000);
                        }

                    }
                });
    }


    private void setupVolume() {
        AudioManager mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        int max = NetConst.RELEASE_SERVER ? mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC) : 0;
        mAudioManager.adjustStreamVolume(AudioManager.STREAM_MUSIC, AudioManager.ADJUST_RAISE, 0);
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, max, 0);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventCheckTime(CheckTime checkTime) {
        EventBus.getDefault().removeStickyEvent(checkTime);
        if (checkTime.status) {
            isCheckTimeSucess = true;
            showToast("校准设备时间成功");
            tvAuthing.setText(R.string.check_version_updating);
            AppUpdateManager instance = AppUpdateManager.getInstance();
            instance.setOnUpdateListener(this);
            instance.getUpdateInfo(this);
        } else {
            isCheckTimeSucess = false;
            String str = getString(R.string.check_system_time_failed);
            if (!NetworkUtils.isNetworkAvaliable(this) && !NetworkUtils.ping()) {
                str = str + "\n" + getString(R.string.network_is_error);
            }
            tvAuthing.setText(str);
            btnResend.setText("重新校准时间");
            btnResend.setTag(BTN_TIME_TAG);
        }
    }

    /**
     * 检查APN设置
     */
    private void checkApnSetting() {
        try {
            if (!TextUtils.equals(TerminalApplication.channelModel, Const.QHYC_C103)) {
                ApnUtils apnUtils = new ApnUtils(this);
                int apnId = apnUtils.isUNIApnExisted();
                if (-1 != apnId) {
                    apnUtils.setDefaultApn(apnId);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取升级信息回调监听
     *
     * @param isUpdate 是否升级
     */
    @Override
    public void getUpdateInfoSucess(boolean isUpdate) {
        this.isReady = true;
        this.isUpdate = isUpdate;
        if (!isUpdate) {
            getDefaultConfig();
        } else {
            tvAuthing.setText(R.string.is_updating);
        }
    }

    @Override
    public void getUpdateInfoFailed() {
        this.isReady = true;
        this.isUpdate = false;
        if (NetworkUtils.isNetworkAvaliable(this) && NetworkUtils.ping()) {
            getDefaultConfig();
        } else {
            tvAuthing.setText(R.string.network_is_error);
        }
    }

    /**
     * 当终端tcp通道连接成功，并且终端启动后的检查操作完成
     * 才去获取终端基础信息 0x0701
     *
     * @param code
     */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventChannelConnect(Integer code) {
        if (code == Const.CHANNEL_ACTIVE) {
            EventBus.getDefault().removeStickyEvent(code);
            if (isReady && !isUpdate) {
                getDefaultConfig();
            } else {
                mHandler.sendEmptyMessage(BTN_TIME_TAG);
            }
        }
    }

    /**
     * 获取终端配置
     */
//    private void getDefaultConfig() {
//        tvAuthing.setText(R.string.get_device_base_info);
//        if (!isCheckTimeSucess) {
//            mHandler.sendEmptyMessage(BTN_TIME_TAG);
//            return;
//        }
//        if (TerminalSocketClientManager.getInstance().isConnect()) {
//            btnResend.setVisibility(View.VISIBLE);
//            Terminal0x0701Request ox0701 = new Terminal0x0701Request();
//            // harisucici
//            ox0701.setImei(DeviceUtil.getImei(this, "gsm.mtk.imei", ""));//IMEI
////            ox0701.setImei(DeviceFactory.getInstance().getHardware().getImei(this));//IMEI
//            ox0701.setVender(TerminalApplication.channelModel);//制造商ID
//            ox0701.setModel(TerminalApplication.channelModel);
//            ox0701.setSerialNum(DeviceFactory.hardware.getSerialNumber(this));//sn
//            ox0701.setPasswd(MD5Util.getSystemPass());
//            TerminalSocketClientManager.getInstance().tellWithNoAuth(ox0701);
////            TerminalSocketClientManager_8001.getInstance().tellWithNoAuth(ox0701);
//        }
//    }

    private void getDefaultConfig() {
        tvAuthing.setText(R.string.get_device_base_info);
        if (!isCheckTimeSucess) {
            mHandler.sendEmptyMessage(BTN_TIME_TAG);
            return;
        }
        if (TerminalSocketClientManager.getInstance().isConnect()) {
            btnResend.setVisibility(View.VISIBLE);
            Terminal0x0701Request ox0701 = new Terminal0x0701Request();
            ox0701.setImei(DeviceFactory.getInstance().getHardware().getImei(this));//IMEI
            ox0701.setVender(TerminalApplication.channelModel);//制造商ID
            ox0701.setModel(TerminalApplication.channelModel);
            ox0701.setSerialNum(DeviceFactory.hardware.getSerialNumber(this));//sn
            ox0701.setPasswd(MD5Util.getSystemPass());
            TerminalSocketClientManager.getInstance().tellWithNoAuth(ox0701);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent0x8701Response(Terminal0x8701Response ox8701) {
        EventBus.getDefault().removeStickyEvent(ox8701);
        int result = ox8701.getResult();
        switch (result) {
            case 0://成功
            case 2://终端被注册
                tvAuthing.setText(result == 0 ? R.string.get_terminal_base_info_sucess : R.string.terminal_isRegister);
                if (Const.CLASS_TYPE == ox8701.getType() || Const.SIMULATE_TYPE == ox8701.getType()) {
                    Const.IS_STOP_UPLOAD_GNSS = true;
                }
                if (TerminalApplication.channelModel.equals(Const.QHYC_C103)) {
                    ((QHYC_C103Hardware) DeviceFactory.hardware).setSystemTime(Long.parseLong(ox8701.getSysTime()));
                }
                TerminalBaseInfo terminalBaseInfo = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo();
                if (terminalBaseInfo != null && terminalBaseInfo.getType() != ox8701.getType()) {
                    DaoManager.getInstance().deleUseData();
                }
                Const.SCHOOL_NAME = ox8701.getSchoolName();
                Const.CAR_CODE = ox8701.getIdentification();
                initApi(ox8701.getInscode());
                TerminalBaseInfoDaoManager.getInstance().insertAndUpdateTerminalBaseInfo(ox8701);
                TerminalParameterDaoManager.getInstance().updateTerminalParameterWith0x8701(ox8701);
                TerminalParameterDaoManager.getInstance().updateTerminalParameterById(Const.TermianlParameter.TAKE_PHOTO_INTERVAL_ID, ox8701.getTakePhotoInterval() + "");
                PreferenceManager.putInt(Const.SP_INTERVAL_TIME, ox8701.getTakePhotoInterval());
                PreferenceManager.putInt(Const.SP_SUBJECT_TYPE, ox8701.getType());
                LoginActivity.openLogin(this, ox8701.getType(), ox8701.getDeviceBelong());

//                Intent intent = new Intent();
//                intent.setClass(this, MainActivity.class);
//                startActivity(intent);

//                Intent intent = new Intent();
//                intent.setClass(this, ObdService.class);
//                startService(intent);

                break;
            case 1:
                tvAuthing.setText(R.string.terminal_password_error);
                break;
            case 3:
                tvAuthing.setText(R.string.terminal_not_over_some_operate);
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventObdDate(Map map) {
        Log.e("harisucici","RPM_"+map.get("RPM"));
        Log.e("harisucici","KM_"+map.get("KM"));
        EventBus.getDefault().removeStickyEvent(ObdConnState.class);
    }
    @OnClick({R.id.btn_resend, R.id.btn_tools})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_tools:
                if (DeviceUtils.fastFiveClick()) {
                    DebugActivity.openDebug(this);
                }
                break;
            case R.id.btn_resend:
                if (v.getTag() != null && (int) v.getTag() == BTN_TIME_TAG) {
                    tvAuthing.setText(R.string.check_system_time);
                    DeviceFactory.hardware.setCalibrateTime();
                    btnResend.setTag(null);
                    btnResend.setText(R.string.reload_device_info);
                } else {
                    getDefaultConfig();
                }
                break;
        }
    }

    /**
     * 初始化百度人脸比对Api Token
     *
     * @param groupId
     */
    private void initApi(String groupId) {
        APIService.getInstance().setGroupId(groupId);
        // 用ak，sk获取token, 调用在线api，如：注册、识别等。为了ak、sk安全，建议放您的服务器，
        APIService.getInstance().initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                APIService.getInstance().setAccessToken(result.getAccessToken());
                mHandler.sendEmptyMessage(INIT_API_SUCESS);
            }

            @Override
            public void onError(FaceError error) {
                error.printStackTrace();
            }
        }, this, Config.apiKey, Config.secretKey);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            TerminalSocketClientManager.getInstance().close();
            TerminalSocketClientManager.getInstance().stopSendHead();
            AppManager.getAppManager().AppExit(this, false);
        }
        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        AppUpdateManager.getInstance().unRegisterListener();
    }
}
